﻿using System.Data;
using System.Security.Authentication;
using System.Security.Principal;
using AZROLESLib;

namespace AzManContrib.MVC
{
// ReSharper disable InconsistentNaming
    public static class IPrincipalExtensions
// ReSharper restore InconsistentNaming
    {

        public static bool Can(this IPrincipal user, IAzOperation operation)
        {
            WindowsIdentity userIdentity = user.Identity as WindowsIdentity;

            if (userIdentity == null)
                throw new InvalidCredentialException();

            AzMan.Store.UpdateCache(null);

            IAzManClientContext clientContext = AzMan.Application.InitializeClientContextFromToken(userIdentity.Token);

            return clientContext.AccessCheck(operation);
        }

        public static bool Can(this IPrincipal user, string operationName)
        {
            AzMan.Store.UpdateCache(null);

            IAzOperation operation = AzMan.Application.Operations.FindByName(operationName);
            if(operation == null)
                throw new ObjectNotFoundException(string.Format("Cannot find any operation with name {0}", operationName));

            return Can(user, operation);
        }
    }
}